/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.permission;

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.service.MetaService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.SecurityUserHolder;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.PermissionRpcService;
import com.je.servicecomb.CommonRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/rbac/permission")
public class PermissionController implements CommonRequestService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private PermissionRpcService permissionRpcService;
    @Autowired
    private MetaResourceService metaResourceService;

    /**
     * 清空重复的权限信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removeDulpPerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional
    public BaseRespResult removeDulpPerm(HttpServletRequest request) {
        List<DynaBean> permBeanList = metaService.select("JE_RBAC_PERM", ConditionsWrapper.builder().orderByAsc("SY_CREATETIME", "PERM_CODE"));
        List<String> deletePermIdList = new ArrayList<>();
        Map<String, String> permCodeMap = new HashMap<>();
        for (DynaBean eachBean : permBeanList) {
            if (!permCodeMap.containsKey(eachBean.getStr("PERM_CODE"))) {
                permCodeMap.put(eachBean.getStr("PERM_CODE"), eachBean.getStr("JE_RBAC_PERM_ID"));
            } else {
                deletePermIdList.add(eachBean.getStr("JE_RBAC_PERM_ID"));
            }
        }
        long count = metaService.delete("JE_RBAC_PERM", ConditionsWrapper.builder().in("JE_RBAC_PERM_ID", deletePermIdList));
        return BaseRespResult.successResult(String.format("清空%s条记录", count));
    }

    /**
     * 清空多余的权限关联
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/removeredundPermAssociation", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional
    public BaseRespResult removeredundPermAssociation(HttpServletRequest request) {
        //角色
        List<Map<String, Object>> rolePermList = metaService.selectSql("select * from JE_RBAC_ROLEPERM where JE_RBAC_PERM_ID NOT IN (select JE_RBAC_PERM_ID from JE_RBAC_PERM)");
        List<String> rolePermIdList = new ArrayList<>();
        for (Map<String, Object> each : rolePermList) {
            rolePermIdList.add(each.get("JE_RBAC_ROLEPERM_ID").toString());
        }
        long roleCount = metaService.delete("JE_RBAC_ROLEPERM", ConditionsWrapper.builder().in("JE_RBAC_ROLEPERM_ID", rolePermIdList));
        //部门
        List<Map<String, Object>> deptPermList = metaService.selectSql("select * from JE_RBAC_DEPTPERM where JE_RBAC_PERM_ID NOT IN (select JE_RBAC_PERM_ID from JE_RBAC_PERM)");
        List<String> deptPermIdList = new ArrayList<>();
        for (Map<String, Object> each : deptPermList) {
            deptPermIdList.add(each.get("JE_RBAC_DEPTPERM_ID").toString());
        }
        long deptCount = metaService.delete("JE_RBAC_DEPTPERM", ConditionsWrapper.builder().in("JE_RBAC_DEPTPERM_ID", deptPermIdList));
        //机构
        List<Map<String, Object>> orgPermList = metaService.selectSql("select * from JE_RBAC_ORGPERM where JE_RBAC_PERM_ID NOT IN (select JE_RBAC_PERM_ID from JE_RBAC_PERM)");
        List<String> orgPermIdList = new ArrayList<>();
        for (Map<String, Object> each : orgPermList) {
            orgPermIdList.add(each.get("JE_RBAC_ORGPERM_ID").toString());
        }
        long orgCount = metaService.delete("JE_RBAC_ORGPERM", ConditionsWrapper.builder().in("JE_RBAC_ORGPERM_ID", orgPermIdList));

        //权限组
        List<Map<String, Object>> permGroupPermList = metaService.selectSql("select * from JE_RBAC_PERMGROUPPERM where JE_RBAC_PERM_ID NOT IN (select JE_RBAC_PERM_ID from JE_RBAC_PERM)");
        List<String> permGroupPermIdList = new ArrayList<>();
        for (Map<String, Object> each : permGroupPermList) {
            permGroupPermIdList.add(each.get("JE_RBAC_PERMGROUPPERM_ID").toString());
        }
        long permGroupCount = metaService.delete("JE_RBAC_PERMGROUPPERM", ConditionsWrapper.builder().in("JE_RBAC_PERMGROUPPERM_ID", permGroupPermIdList));

        return BaseRespResult.successResult(String.format("删除无效角色权限：%s条，删除无效部门权限关联：%s条，删除无效机构权限关联：%s条，删除无效权限组权限关联：%s条", roleCount, deptCount, orgCount, permGroupCount));

    }

    @RequestMapping(value = "/quickGranMenuPerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult quickGranMenuPerm(HttpServletRequest request) {
        String menuId = getStringParameter(request, "menuId");
        String productId = getStringParameter(request, "productId");

        if (Strings.isNullOrEmpty(menuId)) {
            return BaseRespResult.errorResult("请选择菜单！");
        }
        if (Strings.isNullOrEmpty(productId)) {
            return BaseRespResult.errorResult("请选择产品！");
        }
        permissionRpcService.quickGrantMenu(productId, menuId);
        return BaseRespResult.successResult("授权成功！","授权成功，将异步重载权限缓存！");
    }

    @RequestMapping(value = "/quickGranFuncPerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult quickGranFuncPerm(HttpServletRequest request) {
        String funcId = getStringParameter(request, "funcId");
        String productId = getStringParameter(request, "productId");

        if (Strings.isNullOrEmpty(funcId)) {
            return BaseRespResult.errorResult("请选择功能！");
        }
        if (Strings.isNullOrEmpty(productId)) {
            return BaseRespResult.errorResult("请选择产品！");
        }
        DynaBean funcInfo = metaResourceService.selectOneByPk("JE_CORE_FUNCINFO", funcId);
        permissionRpcService.quickGranFunc(productId, funcInfo.getStr("FUNCINFO_FUNCCODE"));
        return BaseRespResult.successResult("授权成功！","授权成功，将异步重载权限缓存！");
    }

    @RequestMapping(value = "/quickGranSubFuncPerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult quickGranSubFuncPerm(HttpServletRequest request) {
        String subFuncId = getStringParameter(request, "subFuncId");
        String productId = getStringParameter(request, "productId");
        if (Strings.isNullOrEmpty(subFuncId)) {
            return BaseRespResult.errorResult("请选择子功能！");
        }
        if (Strings.isNullOrEmpty(productId)) {
            return BaseRespResult.errorResult("请选择产品！");
        }
        permissionRpcService.quickGranSubFunc(productId, subFuncId);
        return BaseRespResult.successResult("授权成功！","授权成功，将异步重载权限缓存！");
    }

    @RequestMapping(value = "/quickGranFuncButtonPerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult quickGranFuncButtonPerm(HttpServletRequest request) {
        String funcCode = getStringParameter(request, "funcCode");
        String buttonCode = getStringParameter(request, "buttonCode");
        String productId = getStringParameter(request, "productId");

        if (Strings.isNullOrEmpty(funcCode)) {
            return BaseRespResult.errorResult("请选择功能！");
        }
        if (Strings.isNullOrEmpty(buttonCode)) {
            return BaseRespResult.errorResult("请选择功能按钮！");
        }
        if (Strings.isNullOrEmpty(productId)) {
            return BaseRespResult.errorResult("请选择产品！");
        }

        Map<String, List<String>> funcButtonMap = new HashMap<>();
        funcButtonMap.put(funcCode, Lists.newArrayList(buttonCode));
        permissionRpcService.quickGrantFuncButton(productId, funcButtonMap);
        return BaseRespResult.successResult("授权成功！","授权成功，将异步重载权限缓存！");
    }

    /**
     * 加载功能权限
     *
     * @param request
     * @return
     */
//    @AuthCheckPermissionTemplate(template = {"pc-func-${funcCode}-show"}, params = {"funcCode"})
    @RequestMapping(value = "/loadFuncPerm", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadFuncPerm(HttpServletRequest request) {
        String departmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
        String accountId = SecurityUserHolder.getCurrentAccountId();
        boolean enableSaas = SpringContextHolder.getBean("enableSaas");
        String tenantId = "";
        if (enableSaas) {
            tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        }
        String funcCode = getStringParameter(request, "funcCode");

        if (Strings.isNullOrEmpty(accountId)) {
            return BaseRespResult.errorResult("请先登录再访问！");
        }

        if (Strings.isNullOrEmpty(funcCode)) {
            return BaseRespResult.errorResult("请选择要加载的功能编码！");
        }

        List<String> funcPermissionCodeList = permissionRpcService.findAccountFuncPermissions(departmentId, accountId, tenantId, funcCode);

        return BaseRespResult.successResult(funcPermissionCodeList);
    }

    @RequestMapping(value = "/loadPluginPerm", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadPluginPerm(HttpServletRequest request) {
        String departmentId = SecurityUserHolder.getCurrentAccountDepartment().getId();
        String accountId = SecurityUserHolder.getCurrentAccountId();
        String pluginCode = getStringParameter(request, "pluginCode");
        boolean enableSaas = SpringContextHolder.getBean("enableSaas");
        String tenantId = "";
        if (enableSaas) {
            tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        }
        if (Strings.isNullOrEmpty(accountId)) {
            return BaseRespResult.errorResult("请先登录再访问！");
        }

        if (Strings.isNullOrEmpty(pluginCode)) {
            return BaseRespResult.errorResult("请选择要加载的插件编码！");
        }
        List<String> pluginPermissionCodeList = permissionRpcService.findAccountPluginPermissions(departmentId, accountId, tenantId, pluginCode);
        return BaseRespResult.successResult(pluginPermissionCodeList);
    }

}
